package cn.innosmart.aq.view.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECInitParams;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.kitsdk.ECDeviceKit;
import com.yuntongxun.kitsdk.beans.ECAuthParameters;
import com.yuntongxun.kitsdk.custom.provider.conversation.ECCustomConversationListUIProvider;
import com.yuntongxun.kitsdk.customsize.AQContactActivity;
import com.yuntongxun.kitsdk.db.ContactSqlManager;
import com.yuntongxun.kitsdk.db.IMessageSqlManager;
import com.yuntongxun.kitsdk.fragment.ConversationListFragment;
import com.yuntongxun.kitsdk.listener.OnConnectSDKListener;
import com.yuntongxun.kitsdk.ui.chatting.model.ECConversation;
import com.yuntongxun.kitsdk.ui.group.model.ECContacts;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.innosmart.aq.R;
import cn.innosmart.aq.bean.FriendBean;
import cn.innosmart.aq.bean.GroupBean;
import cn.innosmart.aq.bean.NearByPeople;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.LocationUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.view.activity.base.BaseActivity;
import cn.innosmart.aq.view.fragment.FriendFragment;
import cn.innosmart.aq.view.fragment.NearByFragment;

/**
 * Created by David on 2015/9/15.
 */
public class FriendActivity extends BaseActivity implements
        ConversationListFragment.OnUpdateMsgUnreadCountsListener, INetworkInteractUtil, ECCustomConversationListUIProvider {
    private NetworkInteractUtil networkInteractUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend);
        nearByPeoples = new ArrayList<>();
        groups = new ArrayList<>();
        childs = new HashMap<>();
        setBar();
        assignViews();
        initialFragments();
        initListener();
        vpRuleStep.setAdapter(viewpagerAdapter);
        networkInteractUtil = new NetworkInteractUtil(this);
        loadingDialog();
        updateLocation();
//        connectIM(SharedUtil.getInstance().readUserId());
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("cn.aq.addfriend");
        mFilter.addAction("cn.aq.removefriend");
        registerReceiver(myReceiver, mFilter);
    }

    public void connectIM(final String userId) {
        ECAuthParameters parameters = new ECAuthParameters();
        parameters.setAppKey("8a48b5514e236232014e2d3d4123091f");
        parameters.setUserId(userId);
        parameters.setAppToken("61afb68b8191bf22588ef22dcddbd4c7");
        parameters.setLoginMode(ECInitParams.LoginMode.FORCE_LOGIN);
        parameters.setLoginType(ECInitParams.LoginAuthType.NORMAL_AUTH);
        ECDeviceKit.login(parameters, new OnConnectSDKListener() {
            @Override
            public void onDisconnect(ECError error) {
                // 兼容4.0
                System.out.println("Connect Error");
            }

            @Override
            public void onConnectState(ECDevice.ECConnectState state, ECError error) {
                // 获取当前sdk的连接状态
                if (state == ECDevice.ECConnectState.CONNECT_FAILED) {
                    if (error.errorCode == SdkErrorCode.SDK_KICKED_OFF) {
                        //帐号异地登陆
                        showToast("帐号异地登陆!");
                    } else {
                        //连接状态失败
                        System.out.println("登录失败!");
                        showToast("聊天登陆失败!");
                    }
                    return;
                } else if (state == ECDevice.ECConnectState.CONNECT_SUCCESS) {
                    // 登陆成功
                    System.out.println("登录成功!");
                }
            }

            @Override
            public void onConnect() {
                // 兼容4.0
                System.out.println("Connect IM");
            }
        });
    }

    public void updateLocation() {
        double latitude = 0;
        double longitude = 0;
        JSONObject jsonObject = LocationUtil.getInstance().readLocation(FriendActivity.this);
        JSONObject jsonNearBy = new JSONObject();
        JSONObject jsonRoot = new JSONObject();
        try {
            latitude = jsonObject.getDouble("latitude");
            longitude = jsonObject.getDouble("longitude");
            jsonNearBy.put("latitude", latitude);
            jsonNearBy.put("longitude", longitude);
            jsonRoot.put("location", jsonNearBy);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("latitude=" + latitude + "longitude=" + longitude);
        networkInteractUtil.getFriends(new JSONObject());
        networkInteractUtil.updateLocation(jsonRoot);
        networkInteractUtil.getNearBy(jsonNearBy);
    }


    private FragmentPagerAdapter viewpagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Fragment getItem(int arg0) {
            return mFragments.get(arg0);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }

        @Override
        public Parcelable saveState() {
            return super.saveState();
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
        }
    };
    private int currentIndex;

    private void initListener() {
        /**
         * 设置监听
         */

        vpRuleStep.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // 重置所有TextView的字体颜色
                switch (position) {
                    case 0:
//                        btRuleLeft.setVisibility(View.GONE);
//                        btRuleRight.setText(getString(R.string.activity_auto_next));
                        break;
                    case 1:
//                        btRuleLeft.setVisibility(View.VISIBLE);
//                        btRuleRight.setText(getString(R.string.activity_auto_next));
                        break;
                    case 2:
//                        btRuleLeft.setVisibility(View.VISIBLE);
//                        btRuleRight.setText(getString(R.string.activity_boxmodify_save));
                        break;
                }
                currentIndex = position;
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                /**
                 * 利用position和currentIndex判断用户的操作是哪一页往哪一页滑动
                 * 然后改变根据positionOffset动态改变TabLine的leftMargin
                 */
                if (currentIndex == 0 && position == 0)// 0->1
                {
                } else if (currentIndex == 1 && position == 0) // 1->0
                {
                } else if (currentIndex == 1 && position == 1) // 1->2
                {


                } else if (currentIndex == 2 && position == 1) // 2->1
                {
                }
                if (positionOffset > 0) {
//                    bar.changing(position, currentIndex, positionOffset);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private LinearLayout main;
    private LinearLayout llContent;
    private ViewPager vpRuleStep;
    private LinearLayout ruleBottom;
    private RelativeLayout rlChat;
    private ImageView ivChat;
    private RelativeLayout rlFriend;
    private ImageView ivFriend;
    private RelativeLayout rlNearby;
    private ImageView ivNearby;
    private TextView tvNearby;
    private TextView tvFriend;
    private TextView tvChat;

    private void assignViews() {
        main = (LinearLayout) findViewById(R.id.main);
        llContent = (LinearLayout) findViewById(R.id.ll_content);
        vpRuleStep = (ViewPager) findViewById(R.id.vp_rule_step);
        ruleBottom = (LinearLayout) findViewById(R.id.rule_bottom);
        rlChat = (RelativeLayout) findViewById(R.id.rl_chat);
        ivChat = (ImageView) findViewById(R.id.iv_chat);
        rlFriend = (RelativeLayout) findViewById(R.id.rl_friend);
        ivFriend = (ImageView) findViewById(R.id.iv_friend);
        rlNearby = (RelativeLayout) findViewById(R.id.rl_nearby);
        ivNearby = (ImageView) findViewById(R.id.iv_nearby);
        rlChat.setOnClickListener(mBottomOnClickListener);
        rlFriend.setOnClickListener(mBottomOnClickListener);
        rlNearby.setOnClickListener(mBottomOnClickListener);
        tvNearby = (TextView) findViewById(R.id.tv_nearby);
        tvFriend = (TextView) findViewById(R.id.tv_friend);
        tvChat = (TextView) findViewById(R.id.tv_chat);
    }

    private View.OnClickListener mBottomOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rl_nearby:
                    currentIndex = 2;
                    vpRuleStep.setCurrentItem(2);
                    break;
                case R.id.rl_chat:
                    currentIndex = 0;
                    vpRuleStep.setCurrentItem(0);
                    break;
                case R.id.rl_friend:
                    currentIndex = 1;
                    vpRuleStep.setCurrentItem(1);
                    break;
            }
        }
    };


    private List<Fragment> mFragments = new ArrayList<Fragment>();


    private void initialFragments() {
        ConversationListFragment conversationList = new ConversationListFragment();
        FriendFragment friendFragment = new FriendFragment();
        NearByFragment nearByFragment = new NearByFragment();
        mFragments.add(conversationList);
        mFragments.add(friendFragment);
        mFragments.add(nearByFragment);
    }

    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.toolbar_back);
        toolbar.setTitle("好友");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private final int EXIT = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
            }
        }
    };

    @Override
    public void OnUpdateMsgUnreadCounts() {

    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    public static ArrayList<NearByPeople> nearByPeoples;
    public static ArrayList<GroupBean> groups;
    public static HashMap<String, ArrayList<FriendBean>> childs;

    @Override

    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(networkInteractUtil.UPDATELOCATION)) {
            if (ret == 0) {
                //success

            } else {
                //error
            }
        } else if (flag.equals(networkInteractUtil.NEARBY)) {
            if (ret == 0) {
                //success
                try {
                    JSONArray jsonFriends = ((JSONObject) object).getJSONArray("nearby_people");
                    nearByPeoples.clear();
                    for (int i = 0; i < jsonFriends.length(); i++) {
                        JSONObject jsonFriend = jsonFriends.getJSONObject(i);
                        NearByPeople nearByPeople = new NearByPeople(jsonFriend);
                        if (!nearByPeople.getId().equals(SharedUtil.getInstance().readUserId())) {
                            nearByPeoples.add(nearByPeople);
                        }
                    }
                    hideloadingDialog();
                    if (currentIndex == 2) {
                        ((NearByFragment) mFragments.get(2)).stopFresh();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                //error
            }
        } else if (flag.equals(networkInteractUtil.GETFRIEND)) {
            if (ret == 0) {
                try {
                    JSONArray jsonGroups = ((JSONObject) object).getJSONArray("friends");
                    groups.clear();
                    childs.clear();
                    ArrayList<FriendBean> friendBeans;
                    for (int i = 0; i < jsonGroups.length(); i++) {
                        JSONObject jsonGroup = jsonGroups.getJSONObject(i);
                        GroupBean groupBean = new GroupBean(jsonGroup);
                        JSONArray jsonFriends = jsonGroup.getJSONArray("list");
                        friendBeans = new ArrayList<>();
                        for (int j = 0; j < jsonFriends.length(); j++) {
                            JSONObject jsonFriend = jsonFriends.getJSONObject(j);
                            FriendBean friendBean = new FriendBean(jsonFriend);
                            friendBean.setGroupid(groupBean.getGroupId());
                            if (!ContactSqlManager.hasContact(friendBean.getId())) {
                                ECContacts ecContact = new ECContacts();
                                ecContact.setNickname(friendBean.getNickName());
                                ecContact.setContactid(friendBean.getId());
                                ContactSqlManager.insertContact(ecContact);
                            } else {
                                ECContacts ecContact = ContactSqlManager.getContact(friendBean.getId());
                                if (!ecContact.getNickname().equals(friendBean.getNickName())) {
                                    ecContact.setNickname(friendBean.getNickName());
                                }
                                ContactSqlManager.insertContact(ecContact);
                            }
                            friendBeans.add(friendBean);
                        }
                        childs.put(groupBean.getGroupId(), friendBeans);
                        groups.add(groupBean);
                        System.out.println("childs" + childs + "groups=" + groups.toString());
                        Iterator iterator = childs.entrySet().iterator();
                        ArrayList<String> friends = new ArrayList<>();
                        while (iterator.hasNext()) {
                            Map.Entry entry = (Map.Entry) iterator.next();
                            ArrayList<FriendBean> friendBeanss = (ArrayList<FriendBean>) entry.getValue();
                            for (FriendBean friendBean : friendBeans) {
                                friends.add(friendBean.getId());
                            }
                        }
                        AQContactActivity.setFriends(friends);
                    }
                    ((FriendFragment) mFragments.get(1)).refresh();
//                    hideloadingDialog();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {

            }
        } else if (flag.equals(networkInteractUtil.ADDFRIEND)) {
            if (ret == 0) {
                JSONObject result = (JSONObject) object;
                System.out.println("result=" + result.toString());
                try {
                    String friendid = result.getJSONObject("result").getString("friendid");
                    String groupid = result.getJSONObject("result").getString("groupid");
                    ECContacts ecContact = new ECContacts();
                    for (int i = 0; i < nearByPeoples.size(); i++) {
                        if (nearByPeoples.get(i).getId().equals(friendid)) {
                            FriendBean friendBean = nearByPeoples.get(i).toFriend();
                            ecContact.setNickname(friendBean.getNickName());
                            ecContact.setContactid(friendid);
                            friendBean.setGroupid(groupid);
                            childs.get(groupid).add(friendBean);
                            Intent intent = new Intent();
                            intent.setAction("cn.aq.addfriend.result");
                            intent.putExtra("id", friendid);
                            sendBroadcast(intent);
                        }
                    }
                    System.out.println("ret=" + ContactSqlManager.insertContact(ecContact));
                    ((FriendFragment) mFragments.get(1)).refresh();
                    ((NearByFragment) mFragments.get(2)).refresh();
                    showToast("添加好友成功!");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                showToast("添加好友失败!");
            }
        } else if (flag.equals(networkInteractUtil.REMOVEFRIEND)) {
            if (ret == 0) {
                JSONObject result = (JSONObject) object;
                System.out.println("result=" + result.toString());
                try {
                    String friendid = result.getJSONObject("result").getString("friendid");
                    String groupid = result.getJSONObject("result").getString("groupid");
                    ArrayList<FriendBean> friendBeans = childs.get(groupid);
                    for (int i = 0; i < friendBeans.size(); i++) {
                        FriendBean friendBean = friendBeans.get(i);
                        if (friendBean.getId().equals(friendid)) {
                            AQContactActivity.getFriends().remove(friendid);
                            friendBeans.remove(friendBean);
                            IMessageSqlManager.deleteChattingMessage(friendid);
                            Intent intent = new Intent();
                            intent.setAction("cn.aq.removefriend.result");
                            intent.putExtra("id", friendid);
                            sendBroadcast(intent);
                        }
                    }
                    ((ConversationListFragment) mFragments.get(0)).freshData();
                    ((FriendFragment) mFragments.get(1)).refresh();
                    ((NearByFragment) mFragments.get(2)).refresh();
                    showToast("好友已删除!");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                showToast("删除好友失败!");
            }
        }
    }

    public void addFriend(String uid) {
        JSONObject jsParams = new JSONObject();
        try {
            jsParams.put("friendid", uid);
            jsParams.put("groupid", FriendActivity.groups.get(0).getGroupId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        networkInteractUtil.addFriend(jsParams);
    }

    public void removeFriend(FriendBean friendBean) {
        JSONObject jsParams = new JSONObject();
        try {
            jsParams.put("friendid", friendBean.getId());
            jsParams.put("groupid", friendBean.getGroupid());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        networkInteractUtil.removeFriend(jsParams);
    }

    @Override
    public List<String> getCustomConversationItemLongClickMenu(Fragment f, ECConversation conversation) {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String id = intent.getStringExtra("id");
            if (intent.getAction().equals("cn.aq.addfriend")) {
                System.out.println("添加好友");
                addFriend(id);
            } else if (intent.getAction().equals("cn.aq.removefriend")) {
                System.out.println("删除好友");
                Iterator iterator = childs.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    ArrayList<FriendBean> friendBeans = (ArrayList<FriendBean>) entry.getValue();
                    for (int i = 0; i < friendBeans.size(); i++) {
                        if (id.equals(friendBeans.get(i).getId())) {
                            removeFriend(friendBeans.get(i));
                            break;
                        }
                    }
                }
            }
        }
    };
}
